<?php

namespace app\common\service;
use app\common\model\RuinuoDatabase as DataMode;
use think\facade\Config;
use think\facade\Db;
use app\ruinuo\design\Curd as ThatCurd;
class DataBase
{
    public function AddEdit($params = [])
    {

        $params['old_name'] = !empty($params['old_name']) ? $params['old_name'] : $params['name'];
        $newTable = Config::get('database.connections.mysql.prefix') . $params['name'];
        $oldTable = Config::get('database.connections.mysql.prefix') . $params['old_name'];
        $collation = explode('utf8mb4', $params['collation']);
        $CHARACTER = 'utf8';
        if (count($collation) >= 2) {
            $CHARACTER = 'utf8mb4';
        }
        if ($params['name'] != $params['old_name']) {
            Db::query("ALTER TABLE `" . $oldTable . "` RENAME TO `" . $newTable . "`");
        } else {
            $sql = "SHOW TABLES LIKE '" . $newTable . "'";
            if (count(Db::query($sql)) == 0) {
                $valFiled = "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',";
                $sql = "CREATE TABLE " . $newTable . "( " .
                    $valFiled .
                    "PRIMARY KEY (id) USING BTREE)ENGINE = " . $params['engine'] . " AUTO_INCREMENT = 1 CHARACTER SET = " . $CHARACTER . " COLLATE = " . $params['collation'] . " COMMENT = '" . $params['comment'] . "' ROW_FORMAT = Dynamic;";
                Db::query($sql);
            }
        }
        Db::query("ALTER TABLE `" . $newTable . "` COMMENT '" . $params['comment'] . "' CHARACTER SET = " . $CHARACTER . " COLLATE = " . $params['collation'] . " COMMENT = '" . $params['comment'] . "'");
        if (count(Db::query("Describe `" . $newTable . "` create_time")) == 0) {
            Db::query("alter table `" . $newTable . "` add `create_time` datetime(0) NULL DEFAULT NULL COMMENT '新增时间'");
        }
        if (count(Db::query("Describe `" . $newTable . "` create_id")) == 0) {
            Db::query("alter table `" . $newTable . "` add `create_id` int(11) NULL DEFAULT 0 COMMENT '新增人'");
        }

        if (count(Db::query("Describe `" . $newTable . "` update_time")) == 0) {
            Db::query("alter table `" . $newTable . "` add `update_time` datetime(0) NULL DEFAULT NULL COMMENT '新增时间'");
        }
        if (count(Db::query("Describe `" . $newTable . "` update_id")) == 0) {
            Db::query("alter table `" . $newTable . "` add `update_id` int(11) NULL DEFAULT 0 COMMENT '修改人'");
        }

        $newField = json_decode($params['field'], true);
        $oldField = Db::query("SHOW FULL COLUMNS FROM " . $newTable);
        $NewFieldStr = '';
        $OldFieldStr = '';
        foreach ($oldField as $k => $v) {
            $OldFieldStr .= '[' . $v['Field'] . ']';
        }
        foreach ($newField as $k => $v) {
            $v['old_field'] = !empty($v['old_field']) ? $v['old_field'] : $v['field'];
            $v['default'] = isset($v['default']) ? $v['default'] : '';
            $v['length'] = isset($v['length']) ? $v['length'] : '';
            $v['key'] = !empty($v['key']) ? $v['key'] : '';
            $NewFieldStr .= '[' . $v['field'] . ']';
            if ($v['field'] != 'id' && $v['field'] != 'create_time' && $v['field'] != 'create_id' && $v['field'] != 'update_time' && $v['field'] != 'update_id') {
                $sql = "ALTER TABLE `" . $newTable . "`";
                $type = 'ADD';
                $count = count(explode('[' . $v['field'] . ']', $OldFieldStr));
                if ($count >= 2) {
                    $type = 'MODIFY';
                }
                if ($v['field'] != $v['old_field']) {
                    $type = ' CHANGE ' . $v['old_field'];
                }
                $sql .= $type;
                $sql .= " `" . $v['field'] . "`";
                switch ($v['type']) {
                    case "longtext":
                    case "text":
                    case "timestamp":
                    case "date":
                    case "json":
                    case "datetime":
                        $sql .= ' ' . $v['type'];
                        break;
                    case "varchar":
                        $v['length'] = $v['length'] ?: '50';
                        $sql .= ' ' . $v['type'] . '(' . $v['length'] . ')';
                        break;
                    case "int":
                        $v['length'] = $v['length'] ?: '11';
                        $sql .= ' ' . $v['type'] . '(' . $v['length'] . ')';
                        break;
                    case "float":
                    case "decimal":
                        $v['length'] = $v['length'] ?: '10,2';
                        $sql .= ' ' . $v['type'] . '(' . $v['length'] . ')';
                        break;
                }

                if ($v['default'] != "" || $v['default'] == "0") {
                    $sql .= " NULL DEFAULT " . $v['default'];
                } else {
                    $sql .= " NULL";
                }
                $sql .= " COMMENT '" . $v['title'] . "'";
                Db::query($sql);
                if ($v['field'] != $v['old_field']) {
                    $query = "SHOW INDEXES FROM `$newTable` WHERE Key_name = '" . $v["old_field"] . "'";
                    if (!empty(Db::query($query))) {
                        Db::query("ALTER TABLE " . $newTable . " drop INDEX index_" . $v["old_field"]);
                    }
                } else {
                    $query = "SHOW INDEXES FROM `$newTable` WHERE Key_name = '" . $v["field"] . "'";
                    if (!empty(Db::query($query))) {
                        Db::query("ALTER TABLE " . $newTable . " drop INDEX index_" . $v["field"]);
                    }
                }
                if ($v['key'] == 1) {
                    Db::query("ALTER TABLE " . $newTable . " ADD INDEX index_" . $v["field"] . " (" . $v["field"] . ")");
                }
            }
        }
        $oldField = Db::query("SHOW FULL COLUMNS FROM " . $newTable);
        foreach ($oldField as $k => $v) {
            $count = count(explode('[' . $v['Field'] . ']', $NewFieldStr));
            if ($count <= 1) {
                Db::query("ALTER TABLE " . $newTable . " DROP " . $v['Field']);
            }
        }
        $ThatCurd = new ThatCurd();
        $ThatCurd->ModePhp(['mode' => ['database' => $newTable]]);
        return [];
    }


    public function Sync($table_name = '')
    {
        $Model = new DataMode();
        $ThatCurd = new ThatCurd();
        $prefix = Config::get('database.connections.mysql.prefix');
        $t = Config::get('database.connections.mysql.database');
        $where = "`TABLE_SCHEMA`='" . $t . "'";
        if ($table_name) {
            $where .= " and `TABLE_NAME`='" . $prefix . "_" . $table_name . "'";
        }
        $arr = Db::query("select * from INFORMATION_SCHEMA.TABLES where " . $where);
        $inData = [];
        $tableStr = '';
        foreach ($arr as $k => $v) {
            $field = Db::query("SHOW FULL COLUMNS FROM " . $v['TABLE_NAME']);
            $infield = [];
            foreach ($field as $kk => $vv) {
                $key = 2;
                if ($vv['Key'] && $vv['Key'] != "PRI") {
                    $key = 1;
                }
                $type = explode("(", $vv['Type']);
                if (count($type) == 2) {
                    $type = $type[0];
                    $result = array();
                    preg_match_all("/(?:\()(.*)(?:\))/i", $vv['Type'], $result);
                    $length = $result[1][0];
                } else {
                    $type = $vv['Type'];
                    $length = 0;
                }
                $infield[] = [
                    'field' => $vv['Field'],
                    'old_field' => $vv['Field'],
                    'title' => $vv['Comment'],
                    'type' => $type,
                    'length' => $length,
                    'default' => $vv['Default'],
                    'key' => $key,
                ];
            }
            $name = str_replace($prefix, '', $v['TABLE_NAME']);
            $tableStr.= "'" . $name . "',";
            $data = [
                'name' => $name,
                'old_name' => $name,
                'comment' => $v['TABLE_COMMENT'],
                'engine' => $v['ENGINE'],
                'rows' => Db::name($name)->count(),
                'collation' => $v['TABLE_COLLATION'],
                'field_num' => count($infield),
                'field' => json_encode($infield, JSON_UNESCAPED_UNICODE),
                'create_time' => date('Y-m-d H:i:s'),
                'create_id' => GetToken('id'),
            ];
            $find = $Model->where("name='" . $name . "'")->field("id")->findOrEmpty()->toArray();
            if (!empty($find['id'])) {
                $data['id'] = $find['id'];
            }
            $ThatCurd->ModePhp(['mode' => ['database' => $name]]);
            $inData[] = $data;
        }
        if ($inData) {
            if (empty($table_name)) {
                $Model->where('name NOT IN(' . rtrim($tableStr, ",") . ')')->delete();
            }
            $Model->saveAll($inData);
        }
        return [];
    }




}